/**
 * Created by chris on 16/9/27.
 */

angular.module('starter.service', [])
.factory('HotsFactory', function ($resource, G, $rootScope) {

    var resource = $resource(G.api, {}, {
        query:{
            method: 'get',
            timeout: 20000
        }
    })

    var data = {};

    return {

        //异步请求
        getHots: function (catid) {
            resource.query({
                //url中的参数
                a: 'getPortalList',
                catid: catid,
                page: 2
            }, function (r) {
                // console.log(r);
                //通知controller拿数据
                data.result = r.result;
                $rootScope.$broadcast('updateHots');
            })

        },
        getHotsData: function () {
            return data.result;
        }
    }
})
.factory('HotsDetailFactory', function ($resource, G, $rootScope) {

    var resource = $resource(G.api, {}, {
        query:{
            method: 'get',
            timeout: 20000
        }
    });

    var data = {};

    return {
        getHotsDetail: function (aid) {
            resource.query({
                a: 'getPortalArticle',
                aid: aid
            }, function (r) {
                data.result = r.result;
                $rootScope.$broadcast('updateHotsDetail');
            })
        },
        getHotsDetailData: function () {
            return data.result[0].content;
        }
    }
    
})
.factory('User', function ($resource, G, $rootScope) {
    var resource = $resource(G.api+'?a=login2');
    var user;
    return {
        login: function (username, password) {
            //save POST请求
            resource.save({
                username: username,
                password: password
            }, function (r) {
                console.log(r);
                user = r.result;
                $rootScope.$broadcast('loginUpdate');
            })
        },
        logout: function () {
            
        },
        getCurrentUser: function () {
            return user;
        }
    }
})
.factory('Storage', function () {
    return {
        set: function (key, data) { 
            return window.localStorage.setItem(key, window.JSON.stringify(data)); 
        }, 
        get: function (key) { 
            return window.JSON.parse(window.localStorage.getItem(key)); 
        }, 
        remove: function (key) { 
            return window.localStorage.removeItem(key); 
        }
    }
})











